<template>
  <el-card class="guest-container">
    <template #header>
      <div class="header">
        <el-input class="search" v-model="searchVal.nickName" size="small" placeholder="请输入昵称" />
        <el-input class="search" v-model="searchVal.loginName" size="small" placeholder="请输入手机号"  />
        <el-button type="primary" :icon="Search" @click="search">搜索</el-button>
        <el-button type="" :icon="RefreshRight" @click="reset">重置</el-button>
        <el-button type="primary" :icon="CirclePlus" @click="addUserDialog = true">新增用户</el-button>
        <el-button type="success" :icon="ShoppingCart" @click="handleAddMoney">批量充值</el-button>
        <el-button type="primary" :icon="Plus" @click="handleSolve">解除禁用</el-button>
        <el-button type="danger" :icon="Delete" @click="handleForbid">禁用账户</el-button>
      </div>
    </template>
    <el-table :load="state.loading" :data="state.tableData" tooltip-effect="dark" style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="nickName" label="昵称" />
      <el-table-column prop="loginName" label="登录名" />
      <el-table-column label="可用余额" >
        <template #default="scope">
          <span> {{ scope.row.remainMoney??'0' }} 元</span>
        </template>
      </el-table-column>
      <el-table-column label="身份状态">
        <template #default="scope">
          <span :style="scope.row.lockedFlag == 0 ? 'color: green;' : 'color: red;'">
            {{ scope.row.lockedFlag == 0 ? '正常' : '禁用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否注销">
        <template #default="scope">
          <span :style="scope.row.isDeleted == 0 ? 'color: green;' : 'color: red;'">
            {{ scope.row.isDeleted == 0 ? '正常' : '注销' }}
          </span>

        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间">
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <span :style="scope.row.lockedFlag == 0 ? 'color: red;' : 'color: green;'"
            style="margin-right:10px;cursor: pointer;" @click="changeLock(scope.row)">
            {{ scope.row.lockedFlag == 0 ? '禁用' : '解禁' }}
          </span>
          <a style="cursor: pointer; margin-right: 10px" @click="openAdd(scope.row)">充值</a>
          <el-popconfirm title="确认删除该会员吗？" @confirm="deleteItem(scope.row)">
            <template #reference>
              <a style="cursor: pointer; margin-right: 10px" >删除</a>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination 
      background layout="prev, pager, next" 
      :total="state.total" 
      :page-size="state.pageSize"
      :current-page="state.currentPage" 
      @current-change="changePage" />
  </el-card>
  
  <el-dialog v-model="addMoneyDialog" title="金额充值" style="width: 600px;">
    <el-card class="add-container">
      <el-form  label-width="100px" class="goodForm" >
        <el-form-item label="用户昵称" >
          <span>{{paramsVal.nickName}}</span>
        </el-form-item>
        <el-form-item label="用户账号" >
          <span>{{paramsVal.loginName}}</span>
        </el-form-item>
        <el-form-item label="账户余额" >
          <span>{{paramsVal.remainMoney||0}}</span>
        </el-form-item>
        <el-form-item label="充值金额" >
          <el-input-number  min="0" :precision="2" :step="100"  style="width: 300px" v-model="paramsVal.addMoney" placeholder="请输入充值的金额"></el-input-number>
        </el-form-item>
      </el-form>
    </el-card>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="setRemainMoney"> 充值</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="AllAddMoneyDialog" title="批量充值" style="width: 600px;">
    <el-card class="add-container">
      <el-form  label-width="100px" class="goodForm" >
        <el-form-item label="充值金额" >
          <el-input-number  min="0" :precision="2" :step="100"  style="width: 300px" v-model="addAllMoney" placeholder="请输入充值的金额"></el-input-number>
        </el-form-item>
      </el-form>
    </el-card>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="setAllRemainMoney"> 充值</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="addUserDialog" title="新增用户" style="width: 600px;" >
    <el-card class="add-container">
      <el-form  label-width="100px" class="goodForm" :model="addInfo.user" :rules="addInfo.rules" ref="addUserRef" >
        <el-form-item label="用户昵称" prop="nickName">
          <el-input  v-model="addInfo.user.nickName" placeholder="请输入用户昵称"></el-input>
        </el-form-item>
        <el-form-item label="用户账号" prop="loginName">
          <el-input  v-model="addInfo.user.loginName" placeholder="请输入账号或手机号" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item label="账户余额" prop="remainMoney">
          <el-input-number v-model="addInfo.user.remainMoney" min="0" :precision="2" :step="100"   placeholder="请输入充值的金额"></el-input-number>
        </el-form-item>
        <el-form-item label="身份状态" prop="lockedFlag">
          <el-select  v-model="addInfo.user.lockedFlag">
            <el-option  label="启用" :value="0"></el-option>
            <el-option  label="禁用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input  type="password" minlength="6" v-model="addInfo.user.password" placeholder="请输入登录密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input  type="password" minlength="6" v-model="addInfo.user.password2" placeholder="请输入确认密码"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="addVipUser"> 充值</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive ,getCurrentInstance,onMounted} from 'vue';
import Table from '@/components/Table.vue';
import { ElMessage } from 'element-plus';
import { Plus, Delete, ShoppingCart ,RefreshRight,Search, CirclePlus} from '@element-plus/icons-vue';
import axios from '@/utils/axios';

const app = getCurrentInstance();
const { goTop } = app.appContext.config.globalProperties;

const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  multipleSelection: []
});
const addInfo = reactive({
  user:{
    nickName: "",
    loginName: "",
    lockedFlag: 0,
    isDeleted: 0,
    password: "",
    password2: "",
    remainMoney: 0,
  },
  rules:{
    nickName: [
      { required: 'true', message: '请输入用户昵称', trigger: ['change'] }
    ],
    loginName: [
      { required: 'true', message: '请输入登录账号或手机号', trigger: ['change'] }
    ],
    password: [
      { required: 'true', message: '请输入密码', trigger: ['change'] }
    ],
    password2: [
      { required: 'true', message: '请输入确认密码', trigger: ['change'] }
    ],
    remainMoney: [
      { required: 'true', message: '请输入账户余额', trigger: ['change'] }
    ],
  }
})

const addMoneyDialog = ref(false)
const AllAddMoneyDialog = ref(false)
const addUserDialog = ref(false)
const paramsVal =reactive({
  addMoney:100
})
const addAllMoney = ref(0)
const addUserRef = ref(null)
onMounted(() => {
  getList();
});

const getList = () => {
  state.loading = true;
  axios.get('/users', {
    params: {
      pageNumber: state.currentPage,
      pageSize: state.pageSize,
      nickName: searchVal.nickName,
      loginName: searchVal.loginName
    }
  }).then(res => {
    state.tableData = res.list;
    state.total = res.totalCount;
    state.currentPage = res.currPage;
    state.loading = false;
    goTop && goTop(); // 回到顶部
  });
};
const searchVal = reactive({
  nickName: '',
  loginName: '',
});
const search = () => {
  Object.assign(state, {
    loading: true,
    tableData: [],
    total: 0,
    currentPage: 1,
    pageSize: 15
  });
  getList();
};
const reset =()=>{
  searchVal.nickName = ''
  searchVal.loginName = ''
  search()
}
const handleSelectionChange = (val) => {
  state.multipleSelection = val;
};

const changePage = (val) => {
  state.currentPage = val;
  getList();
};


const handleSolve = () => {
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择项');
    return;
  }
  axios.put(`/users/0`, {
    ids: state.multipleSelection.map(item => item.userId)
  }).then(() => {
    ElMessage.success('解除成功');
    getList();
  });
};
const handleForbid = () => {
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择项');
    return;
  }
  axios.put(`/users/1`, {
    ids: state.multipleSelection.map(item => item.userId)
  }).then(() => {
    ElMessage.success('禁用成功');
    getList();
  });
};
const changeLock = (item) => {
  axios.put(`/users/${item.lockedFlag == 0 ? 1 : 0}`, {
    ids: [item.userId]
  }).then(() => {
    ElMessage.success(item.lockedFlag == 0 ? '禁用成功' : '解禁成功');
    getList();
  });
};
// 批量充值
const handleAddMoney = () => {
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择项');
    return;
  }
  AllAddMoneyDialog.value = true
  // ids: state.multipleSelection.map(item => item.userId)
};
// 批量充值
const setAllRemainMoney = ()=>{
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择修改项');
    return;
  }
  axios.put(`/updateUserRemainMoney/`+addAllMoney.value, {
    ids: state.multipleSelection.map(item => item.userId)
  }).then(() => {
    ElMessage.success('余额批量增加成功！');
    getList();
  }).finally(() =>{
    AllAddMoneyDialog.value = false;
    addAllMoney.value = 0
  });
}
const deleteItem = (item) => {
  axios.post(`/user/delete/`,{
   userId: item.userId, 
  }).then(() => {
    ElMessage.success('会员删除成功');
    getList();
  })
};
const openAdd = (item) =>{
  console.log(item);
  addMoneyDialog.value =true;
  Object.assign(paramsVal,item)
}
const setRemainMoney = ()=>{
  if(!paramsVal.addMoney) {
    ElMessage.success('请输入充值的金额');
    return false;
  }
  axios.put(`/updateUserRemainMoney/`+paramsVal.addMoney, {
    ids: [paramsVal.userId]
  }).then(() => {
    ElMessage.success('余额充值增加成功！');
    getList();
  }).finally(() =>{
    paramsVal.addMoney = 100
    addMoneyDialog.value = false
  });
}

const addVipUser = ()=>{
  addUserRef.value.validate((vaild) => {
    if (vaild) {
     if(addInfo.user.password != addInfo.user.password2) return ElMessage.success('两次密码输入不一致请检查');
      axios.post('/user/register',addInfo.user).then(() => {
        addUserDialog.value = false
        ElMessage.success('新增会员成功');
        addInfo.user = {}
        getList();
      })
    }
  })
}
</script>

<style>
.guest-container {
  min-height: 100%;

  .header {
    display: flex;

    .search {
      width: 200px;
      margin-right: 10px;
    }
  }
}
</style>